package com.bosssoft.common.annotation.aspect;

/**
 * @className: PublicObjectFieldSetterAspect
 * @description:
 * @author: LiPing
 * @date: 2024/5/3016:28
 * @since 1.0
 **/



import com.bosssoft.common.annotation.PublicObjectFieldSetter;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * 切面类，用于处理 @PublicObjectFieldSetter 注解，实现公共字段赋值。
 * @author LiPing
 */
@Aspect
@Component
public class PublicObjectFieldSetterAspect {

    @Before("@annotation(publicObjectFieldSetter)")
    public void setPublicField(JoinPoint joinPoint, PublicObjectFieldSetter publicObjectFieldSetter) throws IllegalAccessException {
        String fieldName = publicObjectFieldSetter.fieldName();
        String fieldValue = publicObjectFieldSetter.fieldValue();
        Object[] args = joinPoint.getArgs();

        for (Object arg : args) {
            Field field;
            try {
                field = arg.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                field.set(arg, fieldValue);
            } catch (NoSuchFieldException e) {
                // 忽略没有该字段的参数
            }
        }
    }
}

